package com.gl.MyAgent;

import java.io.ByteArrayInputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

import javassist.ClassPool;
import javassist.CtBehavior;
import javassist.CtClass;

public class MyClassFileTransFormer implements ClassFileTransformer {

	@Override
	public byte[] transform(ClassLoader loader, 
							String className, 
							Class<?> classBeingRedefined,
							ProtectionDomain protectionDomain, 
							byte[] classfileBuffer) throws IllegalClassFormatException {
		
		byte[] transformed = null;
		System.out.println("操作类：" + className);
		ClassPool pool =  ClassPool.getDefault();
		CtClass cl = null;
		try {
			cl = pool.makeClass(new ByteArrayInputStream(classfileBuffer));
			
			if ( !cl.isInterface()) {
				
				CtBehavior[] methods = cl.getDeclaredBehaviors();
				for (int i = 0; i < methods.length; i++) {
					CtBehavior moehod = methods[i];
					if (!moehod.isEmpty()) {
						moehod.insertBefore("System.out.println(\" 这个方法开始执行！\"); ");
						moehod.insertAfter("System.out.println(\" 这个方法结束执行！\"); ");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (cl != null)
				cl.detach();
		}
		
		return transformed;
	}

}
